#!/usr/bin/env python
# encoding: utf-8
"""
homeRange.py

Created by Brant Faircloth on 2008-02-11.
Copyright (c) 2008 Brant Faircloth. All rights reserved.

Estimates the h value for individuals by outputting the h of all individuals
where lscv converges (and does not).  The user can then choose which individual
h values to average across.

"""

import MySQLdb, sys
from rpy import *



class homeRange:
    
    """ class for home range analysis in R """
    
    def getList(self):
        
        """get unique list of bird_ids from mysql"""
        database = MySQLdb.connect("params")
        cursor = database.cursor() 
        query = "SELECT DISTINCT(bird_id) FROM ttrs_telemetry WHERE date BETWEEN '2005-01-01' and '2005-04-15' ORDER BY RAND()"
        cursor.execute(query)
        self.id = cursor.fetchall()
    
    def rSetup(self):
        
        """ setup R for kernel HR """
        
        set_default_mode(NO_CONVERSION)
        r.library("adehabitat")
        r.library("RMySQL")
    
    def rRun(self):

        """ runs the actual analysis in R """ 

        r("drv = MySQL()")
        r("con = dbConnect(drv, group='')")
        file = open('KHR_data.csv', 'w')
        file.write('bird_id, convergence, lscv_h\r\n')
        hValueList = []
        
        print 'Estimating Average H for Sample\n'
        
        for element in self.id:
            id = element[0]
            try:
                r(("data = dbGetQuery(con, paste(\"select bird_id, date, x_coord, y_coord from ttrs_telemetry where bird_id = %s and date between '2005-01-01' and '2005-04-15' and (x_coord != 'NULL' or y_coord != 'NULL')\"))") % (id))
                r("loc = data[, c('x_coord','y_coord')]")
                r("id = data[, c('bird_id')]")
                r("ud = kernelUD(loc,id, h = 'LSCV')")
                r("udvol=getvolumeUD(ud)")
                #r(("export.asc(udvol$'%s'$UD,'/users/bcf/Desktop/hr1/%s_hr1.asc')") % (id, id))
                set_default_mode(BASIC_CONVERSION)
                convergence = r(("ud$'%s'$h$convergence") % (id))
                h = r(("ud$'%s'$h$h") % (id))
                if convergence == True:
                    hValueList.append(h)
                    file.write(("'%s',%s,%s\r\n") % (id, convergence, h))
                else:
                    file.write(("'%s',%s,'NA'\r\n") % (id, convergence))
            except:
                file.write(("'%s',%s,%s\r\n") % (id, 'pass', 'too few points'))
                
        #set_default_mode(NO_CONVERSION)
        #averageH = float(sum(hValueList))/len(hValueList)

        #print (('Using Average H (%s) for KHR Estimation\n') % (averageH))
        
        #for element in self.id:
        #    id = element[0]
        #    try:
        #        r(("data = dbGetQuery(con, paste(\"select bird_id, date, x_coord, y_coord from ttrs_telemetry where bird_id = %s and date between '2001-01-01' and '2001-04-15' and (x_coord != 'NULL' or y_coord != 'NULL')\"))") % (id))
        #        r("loc = data[, c('x_coord','y_coord')]")
        #        r("id = data[, c('bird_id')]")
        #        r(("ud = kernelUD(loc,id, h = %s, grid = 90)") % (averageH))
        #        r("udvol=getvolumeUD(ud)")
        #        r(("export.asc(udvol$'%s'$UD,'/users/bcf/Desktop/hr2/%s_hr2.asc')") % (id, id))
        #    except:
        #        pass
                
        r("dbDisconnect(con)")
        file.close()

if __name__=="__main__":
    test=homeRange()
    test.getList()
    test.rSetup()
    test.rRun()

